<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ $route.meta.title }}</span
          ><br /><br />
          <el-button icon="Plus" type="primary" @click="HandleAddTrademark"
            >添加品牌</el-button
          >
        </div>
      </template>
      <div>
        <el-table
          v-loading="tableLoading ? 'loading' : ''"
          :data="trademarkList"
          :border="true"
          style="margin: 10px 0px"
        >
          <el-table-column
            type="index"
            align="center"
            width="80"
            label="序号"
          ></el-table-column>
          <el-table-column label="品牌名称">
            <template #="{ row, $index }">
              <img width="50" height="50" :src="row.logoUrl" :alt="$index" />
            </template>
          </el-table-column>
          <el-table-column prop="tmName" label="品牌LOGO"></el-table-column>
          <el-table-column label="操作">
            <template #="{ row }">
              <el-button
                type="warning"
                size="small"
                icon="Edit"
                @click="HandleUpdateTrademark(row.id)"
                >修改</el-button
              >
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="HandleDeleteTrademark(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="limit"
          :page-sizes="[3, 5, 10, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="prev, pager, next, ->, sizes, jumper, total"
          :total="total"
          @size-change="reqPage"
          @current-change="reqPage"
        />
      </div>
    </el-card>

    <!-- 添加和修改 -->
    <el-dialog
      v-model="DialogAddTrademark"
      :title="DialogMode ? '添加品牌' : '修改品牌'"
      width="40%"
    >
      <span>
        <el-form
          width="80%"
          :rules="addTrademarkFormRules"
          :model="trademarkParams"
          ref="trademarkRef"
        >
          <el-form-item label="品牌名称" label-width="80" prop="tmName">
            <el-input
              placeholder="请输入品牌名称"
              v-model="trademarkParams.tmName"
            ></el-input>
          </el-form-item>
          <el-form-item label="品牌LOGO" label-width="80" prop="logoUrl">
            <el-upload
              class="upload-demo"
              drag
              :action="setting.imgUploadUrl"
              :on-success="uploadDone"
              :on-error="uploadError"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img
                width="150"
                height="150"
                v-if="trademarkParams.logoUrl"
                :src="trademarkParams.logoUrl"
              />
              <template v-else>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽或者 <em>点击上传</em></div>
              </template>
              <template #tip>
                <div class="el-upload__tip">图片大小请控制在500kb以内</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="DialogAddTrademark = false">取消</el-button>
          <el-button
            v-if="DialogMode"
            type="primary"
            @click="submitAddTrademark"
            :disabled="disabledSubmit"
          >
            提交
          </el-button>
          <el-button
            v-else
            type="warning"
            @click="submitUpdateTrademark"
            :disabled="disabledSubmit"
          >
            修改
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除 -->
    <el-dialog
      v-model="DialogDeleteTrademark"
      title="是否删除所选品牌"
      width="30%"
    >
      <el-button @click="DialogDeleteTrademark = false">取消</el-button>
      <el-button type="danger" @click="submitDeleteTrademark"> 确认 </el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
// import { onMounted, reactive, ref, watchEffect } from "vue";
import { useRoute } from "vue-router";
import {
  reqPageTrademark,
  reqSaveTrademark,
  reqGetTrademark,
  reqUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import setting from "@/setting";
import { ElNotification } from "element-plus";

//引入数据类型
import type {
  Records,
  TypePageTrademark,
  Trademark,
} from "@/api/product/trademark/type";

let $route = useRoute();

let DialogAddTrademark = ref<boolean>(false);
let DialogDeleteTrademark = ref<boolean>(false);
let DialogMode = ref<boolean>(true); //true表示添加品牌，false表示修改品牌
let trademarkId = ref<number>(0);
let disabledSubmit = ref<boolean>(false);
let trademarkRef = ref();

//分页初始化数据
let pageNo = ref<number>(1);
let limit = ref<number>(3);
let total = ref<number>(0);
let trademarkList = ref<Records>([]);
let tableLoading = ref<boolean>(false);
//存储品牌数据

//将获取已有品牌的接口封装成函数方便调用
const reqPage = async () => {
  tableLoading.value = true;
  let result: TypePageTrademark = await reqPageTrademark(
    pageNo.value,
    limit.value,
  );
  if (result.code == 200) {
    total.value = result.data.total;
    trademarkList.value = result.data.records;
  }
  tableLoading.value = false;
};

onMounted(() => {
  //页面加载完成初始化一次动态数据
  reqPage();
});

//增删改按钮方法,增和改用同一个对话框组件
const HandleAddTrademark = () => {
  // 方法一：如果第一次组件加载没有form组件，直接调用身上的ref会报错undefinde，可以用ts的?来自动判断是否有该组件
  // trademarkRef.value?.clearValidate('tmName')
  // trademarkRef.value?.clearValidate('logoUrl')

  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  DialogMode.value = true;
  DialogAddTrademark.value = true;
  // 方法二：如果项目没有使用TS，可以使用nextTick解决，但是要注意必须放到组件显示之后
  nextTick(() => {
    trademarkRef.value.clearValidate("tmName");
    trademarkRef.value.clearValidate("logoUrl");
  });
};
let trademarkParams = reactive<Trademark>({
  tmName: "",
  logoUrl: "",
});

const uploadDone = (result: any) => {
  if (result.code == 200) {
    trademarkParams.logoUrl = result.data;
    trademarkRef.value.clearValidate("logoUrl");
  } else {
    ElNotification({
      type: "error",
      title: result.message,
    });
  }
};
const uploadError = (error: any) => {
  ElNotification({
    type: "error",
    title: error,
  });
};

const submitAddTrademark = async () => {
  try {
    await trademarkRef.value.validate();
    let result = await reqSaveTrademark(trademarkParams);
    ElNotification({
      type: result.code == 200 ? "success" : "error",
      title: result.message,
    });
    DialogAddTrademark.value = false;
    //刷新一下列表
    reqPage();
  } catch (error) {
    console.log(error);
  }
};

const HandleUpdateTrademark = async (id: number) => {
  let result = await reqGetTrademark(id);
  if (result.code == 200) {
    trademarkId.value = id;
    trademarkParams.tmName = result.data.tmName;
    trademarkParams.logoUrl = result.data.logoUrl;
    DialogMode.value = false;
    DialogAddTrademark.value = true;
  } else {
    ElNotification({
      type: "error",
      title: "获取数据失败",
    });
  }
};

const submitUpdateTrademark = async () => {
  let data = {
    id: trademarkId.value,
    tmName: trademarkParams.tmName,
    logoUrl: trademarkParams.logoUrl,
  };
  let result = await reqUpdateTrademark(data);
  ElNotification({
    type: result.code == 200 ? "success" : "error",
    title: result.message,
  });
  DialogAddTrademark.value = false;
  //刷新一下列表
  reqPage();
};

const HandleDeleteTrademark = (id: number) => {
  trademarkId.value = id;
  DialogDeleteTrademark.value = true;
};

const submitDeleteTrademark = async () => {
  let result = await reqDeleteTrademark(trademarkId.value);
  ElNotification({
    type: result.code == 200 ? "success" : "error",
    title: result.message,
  });
  DialogDeleteTrademark.value = false;
  //刷新一下列表
  reqPage();
};

//上传前的校验，借鉴于element官网
const beforeAvatarUpload = (rawFile: any) => {
  if (rawFile.type == "image/jpeg" || rawFile.type == "image/png") {
    if (rawFile.size / 1024 / 1024 < 2) {
      return true;
    } else {
      ElNotification.error("图片大小必须小于2mb");
      return false;
    }
  } else {
    ElNotification.error("图片格式只能是jpg或png格式");
    return false;
  }
};

// watchEffect(() => {
//   if (DialogMode.value) {
//     if (trademarkParams.tmName != "" && trademarkParams.logoUrl != "") {
//       disabledSubmit.value = false;
//     } else {
//       disabledSubmit.value = true;
//     }
//   } else {
//     if (
//       trademarkParams.tmName != "" &&
//       trademarkParams.logoUrl != "" &&
//       trademarkId.value != 0
//     ) {
//       disabledSubmit.value = false;
//     } else {
//       disabledSubmit.value = true;
//     }
//   }
// });
//表单校验
const addTrademarkFormRules = {
  tmName: [{ required: true, message: "品牌名称必须填写" }],
  logoUrl: [{ required: true, message: "品牌LOGO必须上传" }],
};
</script>

<style scoped></style>
